import { CK_THEME, CK_THEME_MODE } from '@constants/cache-key';
import { Theme, ThemeMode } from '@constants/theme';
import { cache } from '@utils/cache';
import { reactive, readonly } from 'vue';

export const useTheme = () => {
  const state = reactive<{ mode: string; theme: string }>({
    mode: ThemeMode.DARK, // 默认主题为 light
    theme: Theme.PURPLE,
  });

  const initTheme = () => {
    setTheme(state.theme);
    setMode(state.mode);
  };

  const getTheme = () => {
    return readonly(state);
  };

  const getMode = () => {
    if (state.mode !== ThemeMode.DARK) {
      document.documentElement.classList.remove(ThemeMode.DARK);
    } else {
      document.documentElement.classList.add(ThemeMode.DARK);
    }
    return readonly(state);
  };

  const setTheme = (theme: string) => {
    // TODO: 优化
    document.documentElement.classList.remove(state.theme);
    document.documentElement.classList.add(theme);

    state.theme = theme;
    cache.setItem(CK_THEME, theme);
  };

  const setMode = (mode: string) => {
    state.mode = mode;
    cache.setItem(CK_THEME_MODE, mode);
  };

  return { initTheme, getTheme, setTheme, getMode, setMode };
};
